package com.ksj.Service;


import com.ksj.Utils.DataSorting.DataSortingTool;
import com.ksj.Utils.JdbcTool.JdbcTool;
import com.ksj.Utils.MqttTool.MqttTool;

import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.Listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;


public class MainService {

    private static Logger LOG = LoggerFactory.getLogger(MainService.class);

    public static void startService() {
        //初始化Mqtt
        MqttTool.init();
        //初始化JDBC
        JdbcTool.init();

        MqttTool.listenMgs("UPDATA", new Listener() {
            @Override
            public void onConnected() {

            }

            @Override
            public void onDisconnected() {

            }

            @Override
            public void onPublish(UTF8Buffer utf8Buffer, Buffer buffer, Runnable runnable) {
                try {
                    //System.out.println(RemoteConfigs.getInstance().mysql_host + "&&&&&$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                    String content = new String(buffer.toByteArray(),"UTF8");
                    if (content.length() > 0) {
                        LOG.info(content);
                        DataSortingTool.DataSorting(content);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                LOG.error(throwable.getMessage());
            }
        });

    }

    //停止服务
    public static void stopService(){
        MqttTool.stop(false);
        JdbcTool.stop(false);
    }

    //重启服务
    public static void restart(){
        MqttTool.stop(true);
        JdbcTool.stop(true);
    }

}
